package com.daniel.dianping.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daniel.dianping.dto.Result;
import com.daniel.dianping.entity.Shop;
import com.daniel.dianping.mapper.ShopMapper;
import com.daniel.dianping.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

import static com.daniel.dianping.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author daniel
 * @since 2022-06-29
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result getShopById(Long id) {
        // 获取缓存
        String shopCache = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(shopCache)) {
            // 如果不为空则直接返回数据
            return Result.ok(JSONUtil.toBean(shopCache, Shop.class));
        }
        // 如果空白，应排除为null的情况
        if (shopCache != null) {
            return Result.fail("商铺id不存在！！！");
        }

        // 如果为空则缓存未命中,从数据库查询数据
        Shop shop = getById(id);
        if (shop == null) {
            // 当数据库中没有这个值，则返回""，放置缓存穿透
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_TTL_2, TimeUnit.MINUTES);
            return Result.fail("商铺不存在！！！");
        }
        // 将商铺储存到redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_TTL_30, TimeUnit.MINUTES);
        // 返回数据
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        // id不能为空
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("id不能为空");
        }
        // 更新数据库
        if (!updateById(shop)) {
            log.error("数据库更新失败->" + shop);
        }
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
